package com.dst.note.outline;

import android.app.Dialog;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.TextView;

import com.dst.note.constatns.FileDir;
import com.dst.note.model.Voice;
import com.dst.note.R;
import com.dst.note.utils.FileType;
import com.dst.note.utils.FileUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;

/**
 * 开始录音的 DialogFragment
 * <p>
 * Created by developerHaoz on 2017/8/12.
 */

public class RecordAudioDialogFragment extends DialogFragment {

    private static final String TAG = "RecordAudioDialogFragme";

    private int mRecordPromptCount = 0;

    long timeWhenPaused = 0;

    private Chronometer mChronometerTime;

    public static String mFileDisk;
    private TextView mSaveTv;
    private TextView mCancelTv;
    private MediaRecorder mMediaRecorder;
    private String mPath;

    public static RecordAudioDialogFragment newInstance() {
        RecordAudioDialogFragment dialogFragment = new RecordAudioDialogFragment();
        Bundle bundle = new Bundle();
        dialogFragment.setArguments(bundle);
        return dialogFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFileDisk = FileUtils.getDiskDir(getContext(), FileDir.DIR_VOICE);
        setCancelable(false);
        if (getDialog() != null) {
            getDialog().setCanceledOnTouchOutside(false);
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_record_audio, null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        initView(view);

        builder.setCancelable(false);
        builder.setView(view);
        return builder.create();
    }


    private void initView(View view) {
        mChronometerTime = (Chronometer) view.findViewById(R.id.record_audio_chronometer_time);
        mSaveTv = (TextView) view.findViewById(R.id.save);
        mCancelTv = (TextView) view.findViewById(R.id.cancel);
        mSaveTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopRecord(true);
                dismiss();
            }
        });
        mCancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopRecord(false);
                dismiss();
            }
        });
        startRecord();
    }


    public void startRecord() {
        File folder = new File(mFileDisk);
        if (!folder.exists()) {
            folder.mkdir();
        }
        mChronometerTime.setBase(SystemClock.elapsedRealtime());
        mChronometerTime.start();
        // 开始录音
        /* ①Initial：实例化MediaRecorder对象 */
        if (mMediaRecorder == null) {
            mMediaRecorder = new MediaRecorder();
        }
        try {
            /* ②setAudioSource/setVedioSource */
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
            /*
             * ②设置输出文件的格式：THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式
             * ，H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB)
             */
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            /* ②设置音频文件的编码：AAC/AMR_NB/AMR_MB/Default 声音的（波形）的采样 */
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            /* ③准备 */
            mPath = mFileDisk + File.separator + System.currentTimeMillis() + FileType.TYPE_VOICE;
            mMediaRecorder.setOutputFile(mPath);
            try {
                mMediaRecorder.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /* ④开始 */
            mMediaRecorder.start();
        } catch (IllegalStateException e) {
        }
    }

    public void stopRecord(boolean isSave) {
        mChronometerTime.stop();
        timeWhenPaused = 0;
        if (mMediaRecorder == null) {
            return;
        }
        try {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
        } catch (RuntimeException e) {
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (mPath != null) {
            if (isSave) {
                EventBus.getDefault().post(new Voice(mPath));
            } else {
                new File(mPath).delete();
            }
        }
    }
}
